<template>
  <div>
    <el-row :gutter="15">
<!--      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="small" label-width="100px" label-position="top"-->
<!--               :disabled="setting.readonly">-->
<!--        <template v-if="!loading && formOperates">-->
<!--          <el-col :span="24">-->
<!--            &lt;!&ndash;            finish-status="success"&ndash;&gt;-->
<!--            <el-steps class="steps" simple process-status="process" :active="currentTab" align-center>-->
<!--              <el-step title="基础信息" @click.native="stepChick(0)" style="cursor: pointer "/>-->
<!--              <el-step title="权证信息" @click.native="stepChick(1)" style="cursor: pointer "/>-->
<!--              <el-step title="面积及可租信息" @click.native="stepChick(2)" style="cursor: pointer "/>-->
<!--            </el-steps>-->
<!--            <div v-show="currentTab === 0">-->
<!--              <el-col :span="6" v-if="judgeShow('assetCode')">-->
<!--                <el-form-item label="资产编码"-->
<!--                              prop="assetCode">-->
<!--                  <el-input v-model="dataForm.assetCode"-->
<!--                            placeholder="系统自动生成" :disabled="judgeWrite('assetCode')">-->
<!--                  </el-input>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--              <el-col :span="6" v-if="judgeShow('assetName')"-->
<!--              >-->
<!--                <el-form-item label="项目名称"-->
<!--                              prop="project">-->
<!--                  <el-input v-model="dataForm.project"-->
<!--                            placeholder="请输入" :disabled="judgeWrite('project')" clearable :style='{"width":"100%"}'>-->

<!--                  </el-input>-->
<!--                </el-form-item>-->
<!--              </el-col>-->

<!--            </div>-->


<!--          </el-col>-->


<!--        </template>-->
<!--      </el-form>-->
      <el-form ref="elForm" :model="dataForm" :rules="rules" size="small" label-width="100px" label-position="right">
        <template v-if="!loading">
          <el-col :span="24">
            <el-form-item label-width="0">
              <JNPF-Text :style='{"width":"100%"}'
                         :textStyle='{"color":"#000000","font-weight":"bold","text-decoration":"none","font-size":15,"line-height":32,"font-style":"normal","text-align":"left"}'
                         value="基础信息" :closable="false"
              >
              </JNPF-Text>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="客户名称"
                              prop="customerName"
                >
                  <p>{{dataForm.customerName}}</p>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计费周期"
                              prop="expenseCycleDate"
                >
                  <p>{{dataForm.expenseCycleDate}}</p>

                </el-form-item>
              </el-col>



              <el-col :span="12">
                <el-form-item label="减免日期"
                              prop="receiptAccount"
                >
                  <el-date-picker v-model="dataForm.operateDate"  :disabled="judgeWrite('operateDate')"
                                  placeholder="请选择" clearable :style='{"width":"100%"}' type="date"
                                  format="yyyy-MM-dd"  @change="handleDateChange"
                  >

                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="减免原因"
                              prop="paymentBy"
                >
                  <el-input v-model="dataForm.reason" :disabled="judgeWrite('reason')"
                            placeholder="请输入" clearable :style='{"width":"100%"}'
                  >

                  </el-input>
                </el-form-item>
              </el-col>

            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="附件"
                          prop="file"
            >
              <JNPF-UploadFz  :disabled="judgeWrite('reason')"  v-model="dataForm.filePath"
                             :fileSize="10" sizeUnit="MB" :limit="9" buttonText="点击上传"
              >

              </JNPF-UploadFz>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label-width="0">
              <JNPF-Text :style='{"width":"100%"}'
                         :textStyle='{"color":"#000000","font-weight":"bold","text-decoration":"none","font-size":15,"line-height":32,"font-style":"normal","text-align":"left"}'
                         value="收款明细" :closable="false"
              >
              </JNPF-Text>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="100" style="margin-left: 21px">
              <!--                <div class="JNPF-common-title">-->
              <!--                  <h2 style="font-weight: 600">费用项目明细</h2>-->
              <!--                </div>-->
              <el-table      has-c @selection-change="handleSelectionChange"     :data="dataForm.items" size="mini">
                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>
                <el-table-column type="index" width="50" label="序号" align="center"/>
                <el-table-column  width="150" label="状态" align="status">
                  <template slot-scope="scope">
                    <p v-if="scope.row.status">待收款</p>
                  </template>
                </el-table-column>


                <el-table-column  width="150" prop="expenseItem" label="费用项">
                  <template slot-scope="scope">
                    <!--                      <el-input disabled v-model="scope.row.expenseItem"-->
                    <!--                                placeholder="请输入" readonly clearable :style='{"width":"100%"}'-->
                    <!--                      >-->
                    <!--                      </el-input>-->
                    <!--                      -->
                    <p>{{scope.row.expenseItem}}</p>

                  </template>
                </el-table-column>

                <el-table-column prop="expenseItem"  width="150" label="周期单价">
                  <template slot-scope="scope">

                    <P>{{scope.row.cyclePrice}}({{scope.row.cycleType}})</P>
                  </template>
                </el-table-column>
                <el-table-column prop="expenseItem"   width="100" label="应收">
                  <template slot-scope="scope">

                    <P>{{scope.row.receiveAmount}}</P>
                  </template>
                </el-table-column>
                <el-table-column prop="expenseItem"   width="100" label="待收">
                  <template slot-scope="scope">

                    <P>{{scope.row.pendAmount}}</P>
                  </template>
                </el-table-column>

                <el-table-column prop="expenseItem"   width="200" label="本次减免金额">
                  <template slot-scope="scope">
                    <el-input  :disabled="judgeWrite('reason')" v-model="scope.row.crAmount" @input="check(scope.row)"
                              placeholder="请输入本次减免金额" clearable :style='{"width":"100%"}'
                    >

                    </el-input>
                  </template>
                </el-table-column>


              </el-table>

              <SelectDialog v-if="selectDialogVisible" :config="currTableConf" :formData="dataForm"
                            ref="selectDialog" @select="addForSelect" @close="selectDialogVisible=false"
              />
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit"/>
  </div>
</template>
<script>
import request from '@/utils/request'
import {getDataInterfaceRes} from '@/api/systemData/dataInterface'
import {getDictionaryDataSelector} from '@/api/systemData/dictionary'

export default {
  components: {},
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      setting: {},
      eventType: '',
      currentTab: 0,
      userBoxVisible: false,
      currTableConf: {},
      addTableConf: {},
      tableRows: {},
      dataForm: {
        id: '',
        flowId: '',
        status: 1,
        freeapproveruserid: '',
        flowUrgent: 1,
        assetCode: undefined,
        assetName: undefined,
        assetTags: undefined,
        detailedAddress: undefined,
        assetNature: undefined,
        assetUse: undefined,
        assetSource: undefined,
        propertyRightUnit: undefined,
        managementUnit: undefined,
        managerId: undefined,
        coverPictureUrl: [],
        remark: undefined,
        attachmentUrls: [],
        zc_asset_warrant:
          {
            type: '',
            code: '',
            landUse: '',
            roomUse: '',
            propertyUse: '',
            certifiedAddress: '',
            nowPropertyUse: '',
            landAuthorityNature: '',
            numberOblocks: '',
            generalFloor: '',
            floorNum: '',
            startDate: '',
            endDate: '',
            issueDate: '',
            custodyPlace: '',
            remark: '',
            attachmentUrls: '',
            imageUrl: '',
          },
        zc_asset_area:
          {
            floorArea: '',
            casingArea: '',
            commonArea: '',
            leasableArea: '',
          },
        zc_asset_image:
          {
            imageDate: '',
            imageUrl: '',
          },
        jnpf_zc_asset_warrant_jnpf_type: "",
        jnpf_zc_asset_warrant_jnpf_code: '',
        jnpf_zc_asset_warrant_jnpf_landUse: '',
        jnpf_zc_asset_warrant_jnpf_roomUse: '',
        jnpf_zc_asset_warrant_jnpf_propertyUse: '',
        jnpf_zc_asset_warrant_jnpf_certifiedAddress: '',
        jnpf_zc_asset_warrant_jnpf_nowPropertyUse: '',
        jnpf_zc_asset_warrant_jnpf_landAuthorityNature: "",
        jnpf_zc_asset_warrant_jnpf_numberOblocks: '',
        jnpf_zc_asset_warrant_jnpf_generalFloor: '',
        jnpf_zc_asset_warrant_jnpf_floorNum: 0,
        jnpf_zc_asset_warrant_jnpf_startDate: '',
        jnpf_zc_asset_warrant_jnpf_endDate: '',
        jnpf_zc_asset_warrant_jnpf_issueDate: '',
        jnpf_zc_asset_warrant_jnpf_custodyPlace: '',
        jnpf_zc_asset_warrant_jnpf_remark: '',
        jnpf_zc_asset_warrant_jnpf_attachmentUrls: [],
        jnpf_zc_asset_warrant_jnpf_imageUrl: [],
        jnpf_zc_asset_area_jnpf_floorArea: '',
        jnpf_zc_asset_area_jnpf_casingArea: '',
        jnpf_zc_asset_area_jnpf_commonArea: '',
        jnpf_zc_asset_area_jnpf_leasableArea: '',
        jnpf_zc_asset_image_jnpf_imageDate: '',
        jnpf_zc_asset_image_jnpf_imageUrl: [],
        version: 0,
      },
      tableRequiredData: {},
      activeseldjz: '0',
      dataRule:
        {
          assetName: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          detailedAddress: [
            {
              required: true,
              message: '请输入',
              trigger: 'blur'
            },
          ],
          assetNature: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          assetSource: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          propertyRightUnit: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          managementUnit: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],


          jnpf_zc_asset_warrant_jnpf_type: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          jnpf_zc_asset_image_jnpf_imageDate: [
            {
              required: true,
              message: '请选择',
              trigger: 'change'
            },
          ],
          jnpf_zc_asset_image_jnpf_imageUrl: [
            {
              required: true,
              message: '请至少选择一个',
              trigger: 'click'
            },
          ],


        },
      assetNatureOptions: [],
      assetUseOptions: [],
      assetSourceOptions: [],
      propertyRightUnitOptions: [],
      managementUnitOptions: [],

      jnpf_zc_asset_warrant_jnpf_typeOptions: [],
      jnpf_zc_asset_warrant_jnpf_landAuthorityNatureOptions: [],
    }
  },
  computed: {
    formOperates() {
      return this.setting.formOperates
    }
  },
  watch: {},
  created() {
    this.getassetNatureOptions();
    this.getassetUseOptions();
    this.getassetSourceOptions();
    this.getpropertyRightUnitOptions();
    this.getmanagementUnitOptions();
    this.getjnpf_zc_asset_warrant_jnpf_typeOptions();
    this.getjnpf_zc_asset_warrant_jnpf_landAuthorityNatureOptions();
  },
  mounted() {
  },
  methods: {

    check(scope){

      if(parseFloat(scope.crAmount)  > parseFloat(scope.pendAmount)){

        this.$message({
          message: '减免金额不能大于待收金额',
          type: 'error',
          duration: 1500,
        })
        scope.crAmount = ''
        return
      }
    },

    handleDateChange(value) {
      this.dataForm.operateDate = value ? this.formatDate(value) : '';
    },
    formatDate(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    },
    judgeShow(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return true
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return item.read
    },
    stepChick(currentTab) {
      return this.currentTab = currentTab
    },
    judgeWrite(id) {
      if (!this.setting.formOperates || !this.setting.formOperates.length) return false
      let arr = this.setting.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return true
      let item = arr[0]
      return !item.write
    },
    getassetNatureOptions() {
      getDictionaryDataSelector('610823452110094661').then(res => {
        this.assetNatureOptions = res.data.list
      })
    },
    getassetUseOptions() {
      getDictionaryDataSelector('610823865056100677').then(res => {
        this.assetUseOptions = res.data.list
      })
    },
    getassetSourceOptions() {
      getDictionaryDataSelector('610823965094445381').then(res => {
        this.assetSourceOptions = res.data.list
      })
    },
    getpropertyRightUnitOptions() {
      getDictionaryDataSelector('610824055188095301').then(res => {
        this.propertyRightUnitOptions = res.data.list
      })
    },
    getmanagementUnitOptions() {
      getDictionaryDataSelector('610824142995849541').then(res => {
        this.managementUnitOptions = res.data.list
      })
    },
    getjnpf_zc_asset_warrant_jnpf_typeOptions() {
      getDictionaryDataSelector('610826202277478725').then(res => {
        this.jnpf_zc_asset_warrant_jnpf_typeOptions = res.data.list
      })
    },
    getjnpf_zc_asset_warrant_jnpf_landAuthorityNatureOptions() {
      getDictionaryDataSelector('610826295164535109').then(res => {
        this.jnpf_zc_asset_warrant_jnpf_landAuthorityNatureOptions = res.data.list
      })
    },
    goBack() {
      this.$emit('refresh')
    },
    init(data) {


      console.log(data)
    //判断是发起还是审批，调用不同接口  。如果为审批，就调用审批数据
      if(data.create!= true){

        console.log(data.flowTaskInfo)
        this.dataInfo(JSON.parse(data.flowTaskInfo.flowFormContentJson));
        this.$emit('setPageLoad')
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
        this.loading = false
        // this.dataForm.id = data.id || "";
        this.setting = data;
        // this.visible = true;
        this.updateDataRule()
        // this.$nextTick(() => {
        //   // this.$refs['elForm'].resetFields();
        //
        //   if (this.dataForm.id) {
        //     this.loading = true;
        //     request({
        //       url: '/api/workflow/form/ZcglCwBillOperate/' + this.dataForm.id,
        //       method: 'get'
        //     }).then(res => {
        //       if (res.data ) {
        //         this.dataInfo(res.data);
        //         this.dataForm.expenseCycleDate = this.dataForm.zcBillVO.expenseCycleDate;
        //         this.dataForm.customerName = this.dataForm.zcBillVO.customerName;
        //
        //         // 合并 billitems 和 items
        //         let mergedItems = [];
        //         let billitemsMap = {};
        //
        //         // 将 billitems 转换为 map，以 expenseItem 为 key
        //         res.data.billitems.forEach(item => {
        //           billitemsMap[item.expenseItem] = item;
        //         });
        //
        //         // 遍历 items，合并 billitems 的数据
        //         res.data.items.forEach(item => {
        //           let mergedItem = { ...item };
        //           if (billitemsMap[item.expenseItem]) {
        //             mergedItem = { ...mergedItem, ...billitemsMap[item.expenseItem] };
        //           }
        //           mergedItems.push(mergedItem);
        //         });
        //
        //         // 将合并后的数据赋值给 this.dataForm
        //         this.dataForm.items = mergedItems;
        //       } else {
        //         this.$message.error('获取数据失败，请稍后再试。');
        //       }
        //     }).catch(error => {
        //       console.error('请求失败:', error);
        //       this.$message.error('请求失败，请检查网络连接或稍后再试。');
        //     }).finally(() => {
        //       this.loading = false;
        //     });
        //   }
        //   this.$emit('setPageLoad')
        // })
        // this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      }else{
        this.dataForm.id = data.id || "";
        this.setting = data;
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          // this.$refs['elForm'].resetFields();

          if (this.dataForm.id) {
            this.loading = true
            request({
              url: '/api/zcgl/fico/bill/getBillInfo/' + this.dataForm.id,
              method: 'get'
            }).then(res => {

              res.data.items = res.data.zcbillitemList
              this.dataInfo(res.data)
              this.loading = false
            })
          }
          this.$emit('setPageLoad')
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})

      }



    },
    updateDataRule() {
      let newRules = {}
      for (let i = 0; i < this.setting.formOperates.length; i++) {
        const item = this.setting.formOperates[i]
        if (!item.id.includes('-')) {
          const newRulesItem = {
            required: item.required,
            message: item.name + '不能为空',
            trigger: item.trigger || 'blur'
          }
          if (!this.dataRule.hasOwnProperty(item.id)) {
            if (item.required) this.$set(newRules, item.id, [newRulesItem])
          } else {
            let withoutRequiredItem = true
            for (let i = 0; i < this.dataRule[item.id].length; i++) {
              if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                this.dataRule[item.id][i].required = item.required
                withoutRequiredItem = false
              }
            }
            if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
          }
        } else {
          let key = item.id.split('-')[0]
          let newId = item.id.split('-')[1]
          let newItem = {
            ...item,
            id: newId
          }
          if (!this.tableRequiredData.hasOwnProperty(key)) {
            this.$set(this.tableRequiredData, key, [newItem])
          } else {
            this.tableRequiredData[key].push(newItem)
          }
        }
      }
      this.dataRule = {...this.dataRule, ...newRules}
    },
    exist() {
      let isOk = true
      for (let key in this.tableRequiredData) {
        if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
          for (let i = 0; i < this.dataForm[key].length; i++) {
            let item = this.dataForm[key][i]
            inner: for (let id in item) {
              let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
              if (!arr.length) continue inner
              if (arr[0].required) {
                let msg = `${arr[0].name}不能为空`
                let boo = true
                if (arr[0].dataType === 'array') {
                  boo = !this.jnpf.isEmptyArray(item[id])
                } else {
                  boo = !this.jnpf.isEmpty(item[id])
                }
                if (!boo) {
                  this.$message({
                    message: msg,
                    type: 'error',
                    duration: 1000
                  })
                  isOk = false
                  break
                }
              }
            }
          }
        }
      }
      return isOk
    },
    judgeRequired(id) {
      if (!this.formOperates || !this.formOperates.length) return false
      let arr = this.formOperates.filter(o => o.id === id) || []
      if (!arr.length) return false
      let item = arr[0]
      return item.required
    },
    // 表单提交
    dataFormSubmit(eventType, flowUrgent) {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          if (this.exist && !this.exist()) return
          if (eventType === 'audit' || eventType === 'reject') {
            this.$emit('eventReceiver', this.dataForm, eventType)
            return
          }
          this.dataForm.status = eventType === 'submit' ? 0 : 1
          this.dataForm.flowState = eventType === 'submit' ? 0 : 1
          this.dataForm.flowId = this.setting.flowId
          this.dataForm.flowUrgent = flowUrgent
          this.eventType = eventType
          if (this.eventType === 'submit') {
            this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
              type: 'warning'
            }).then(() => {
              this.request()
            }).catch(() => {
            });
          } else {
            this.request()
          }
        }
      })
    },
    request() {
      var _data = this.dataList()
      var idt = this.dataForm.id

      delete  this.dataForm.id
      //1减免，2为退款
      _data.type = 1
      for (let i = 0; i < _data.items.length; i++) {
        _data.zcbillitemList[i].billItemId= _data.items[i].id
      }
      if (!this.dataForm.id) {
        //关联账单id
        _data.billId = idt
        request({
          url: '/api/workflow/form/ZcglCwBillOperate',
          method: 'post',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      } else {
        request({
          url: '/api/workflow/form/ZcglCwBillOperate/' + this.dataForm.id,
          method: 'PUT',
          data: _data
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.visible = false
              this.$emit('close', true)
            }
          })
        })
      }
    },
    openSelectDialog(key) {
      this.currTableConf = this.addTableConf[key]
      this.currVmodel = key
      this.selectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.selectDialog.init()
      })
    },
    addForSelect(data) {
      for (let i = 0; i < data.length; i++) {
        let item = {...this.tableRows[this.currVmodel], ...data[i]}
        this.dataForm[this.currVmodel].push(item)
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));


      return _data;
    },
    dataInfo(dataAll) {
      dataAll.items = dataAll.zcbillitemList
      let _dataAll = dataAll
      if (typeof _dataAll.filePath === 'string') {
        // 如果 _dataAll.filePath 是字符串，尝试解析为 JSON
        try {
          _dataAll.filePath = _dataAll.filePath ? JSON.parse(_dataAll.filePath) : []
        } catch (e) {
          // 如果解析失败，设置为空数组
          _dataAll.filePath = [];
        }
      } else {
        // 如果已经是 JSON 对象，直接赋值
        _dataAll.filePath = _dataAll.filePath || [];
      }

      //         _dataAll.paymentType = _dataAll.paymentType ? JSON.parse( _dataAll.paymentType):[]
      //         _dataAll.receiptAccount = _dataAll.receiptAccount ? JSON.parse( _dataAll.receiptAccount):[]
      //         _dataAll.paymentBy = _dataAll.paymentBy ? JSON.parse( _dataAll.paymentBy):[]
      //         _dataAll.paymentAccount = _dataAll.paymentAccount ? JSON.parse( _dataAll.paymentAccount):[]
      // _dataAll.filePath = _dataAll.filePath ? JSON.parse(_dataAll.filePath) : []
      for (let i = 0; i < _dataAll.items.length; i++) {
        var _list = _dataAll.items[i]
      }
      this.dataForm = _dataAll
    },
  },
}

</script>
